package com.sgb.kjwl.view.ui.activity.manage.special

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.text.*
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityMemberUnitBinding
import com.sgb.kjwl.databinding.ItemMemberUnitBinding
import com.sgb.kjwl.di.self.DaggerSelfComponent
import com.sgb.kjwl.di.self.SelfModule
import com.sgb.kjwl.model.entity.manage.special.SpecialMemberEntity
import com.sgb.kjwl.viewmodel.manage.MemberUnitViewModel
import com.swgk.core.base.di.AppComponent
import com.swgk.core.dialog.RoundCornerDialog
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration
import com.swgk.core.util.DateUtils
import com.swgk.core.util.SharedPreferenceUtil
import javax.inject.Inject

/**
 * 企业专项 成员单位
 */
class MemberUnitActivity : AppActivity() {

    @Inject
    lateinit var mViewModel : MemberUnitViewModel

    private lateinit var mBinding : ActivityMemberUnitBinding

    private lateinit var mAdapter : MemberUnitAdapter

    private var mSearchName = ""

    private var isLoadMore = false //是否加载更多
    private var isEnableLoadMore = false//是否能加载更多

    companion object{
        fun launch(context: Context){
            val intent  = Intent(context, MemberUnitActivity::class.java)
            context.startActivity(intent)
        }
    }

    override fun setupActivityComponent(appComponent: AppComponent?) {
        super.setupActivityComponent(appComponent)
        DaggerSelfComponent.builder().appComponent(appComponent)
            .selfModule(SelfModule()).build().inject(this)
    }

    override fun initView() {
        super.initView()
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_member_unit)
        mBinding.include.titleView.text = "成员单位"
        mBinding.include.ivBack.setOnClickListener { finish() }
        initRecyclerView()
        mBinding.tvSearchDelete.setOnClickListener {
            mBinding.etView.setText("")
        }
        mBinding.tvSearch.setOnClickListener {
            isLoadMore = false
            getData()
            mAdapter.setHighlightStr(mSearchName)
        }
        mViewModel.mMemberUnitList.observe(this, {
            isEnableLoadMore = it != null && it.size >= 10
            if (it != null){
                if (isLoadMore){
                    mAdapter.addData(it)
                } else {
                    mAdapter.setNewData(it)
                }
            }
        })
        mViewModel.mPosition.observe(this, {
            if (it != null){
                mAdapter.remove(it)
            }
        })
        mBinding.etView.addTextChangedListener(object : TextWatcher{
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                if (s != null) {
                    mBinding.tvSearchDelete.visibility =
                        if (TextUtils.isEmpty(s)) View.GONE else View.VISIBLE
                    mSearchName = s.toString();
                }
            }
        })
    }

    override fun init() {
        super.init()
        isLoadMore = false
        getData()
    }

    @SuppressLint("UseRequireInsteadOfGet")
    private fun initRecyclerView() {
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                getData()
                mBinding.refreshLayout.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                getData()
                mBinding.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                return mBinding.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        mBinding.recycleView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        mBinding.recycleView.setItemViewCacheSize(100)
        mBinding.recycleView.setHasFixedSize(true)
        mAdapter = MemberUnitAdapter(this, R.layout.item_member_unit)
        mAdapter.bindToRecyclerView(mBinding.recycleView)
        val empty = LayoutInflater.from(this).inflate(R.layout.layout_empty_view, mBinding.recycleView, false)
        mAdapter.emptyView = empty
        mBinding.recycleView.addItemDecoration(
            RecyclerCustomDecoration(
                0f,
                0f,
                0f,
                resources.getDimension(R.dimen.dp10), resources.getColor(R.color.color_main_bg)
            )
        )
        mAdapter.setCallBack(object : ClickCallBack{
            override fun clickRelieve(item: SpecialMemberEntity?, position: Int) {
              if (item != null){
                  showDialog(item.id, position)
              }
            }
        })
    }

    private fun showDialog(id : Int, position: Int) {
        val view = View.inflate(activity, R.layout.dialog_two_btn, null)
        val roundCornerDialog = RoundCornerDialog(
            activity, 0, 0, view, R.style.RoundCornerDialog
        )
        roundCornerDialog.show()
        roundCornerDialog.setCanceledOnTouchOutside(false) // 设置点击屏幕Dialog不消失
        val tv_message = view.findViewById<TextView>(R.id.tv_message)
        val tv_logout_confirm = view.findViewById<TextView>(R.id.tv_logout_confirm)
        val tv_logout_cancel = view.findViewById<TextView>(R.id.tv_logout_cancel)
        tv_message.text = "确定解除关系"

        //确定
        tv_logout_confirm.setOnClickListener {
            mViewModel.relieveMember(id, position)
            roundCornerDialog.dismiss()
        }
        //取消
        tv_logout_cancel.setOnClickListener { roundCornerDialog.dismiss() }
    }

    fun getData(){
        mViewModel.getMemberUnitList(mSearchName, isLoadMore);
    }


    class MemberUnitAdapter(mContext : Context, layoutResId : Int) : BaseQuickAdapter<SpecialMemberEntity, BaseViewHolder>(layoutResId){
        private  var mItemBinging : ItemMemberUnitBinding?= null
        private var mColorSpan : ForegroundColorSpan = ForegroundColorSpan(mContext.resources.getColor(R.color.color_title_medium))
        private var mHighlightColorSpan : ForegroundColorSpan = ForegroundColorSpan(mContext.resources.getColor(R.color.color_secondary_blue))
        private var ssb : SpannableStringBuilder?= null

        private var mCallBack : ClickCallBack ?= null

        private var mHighlightStr = ""
        fun setCallBack(callBack : ClickCallBack){
            this.mCallBack = callBack
        }

        fun setHighlightStr(content  : String){
            this.mHighlightStr = content
        }

        override fun convert(helper: BaseViewHolder?, item: SpecialMemberEntity?) {
            mItemBinging = DataBindingUtil.bind(helper!!.itemView)
            if (mItemBinging != null) {
                //mItemBinging!!.tvName.text = item!!.companyName
                setHighlightColorSpan(item!!.companyName, mItemBinging!!.tvName)
                setColorSpan(mContext.resources.getString(R.string.invite_business_address, if(TextUtils.isEmpty(item!!.address)) "" else item.address), mItemBinging!!.tvBusinessAddress)
                setColorSpan(mContext.resources.getString(R.string.invite_business_operation, if (TextUtils.isEmpty(item.business)) "" else item.business), mItemBinging!!.tvBusinessOperation)
                setColorSpan(mContext.resources.getString(R.string.invite_time, if (item.time == 0L) "" else DateUtils.timestampToDateSecond(item.time)), mItemBinging!!.tvTime)
                setColorSpan(mContext.resources.getString(R.string.special_member_contacts, if (TextUtils.isEmpty(item.contacts)) "" else item.contacts), mItemBinging!!.tvContacts)
                setColorSpan(mContext.resources.getString(R.string.special_member_contact_phone, if (TextUtils.isEmpty(item.phone)) "" else item.phone), mItemBinging!!.tvContactNumber)
                mItemBinging!!.tvRelieve.setOnClickListener { //解除
                     if (mCallBack != null){
                         mCallBack!!.clickRelieve(item, helper.layoutPosition)
                     }
                }
            }
        }

        private fun setColorSpan(content: String, tv: TextView) {
            ssb = SpannableStringBuilder(content)
            ssb!!.setSpan(mColorSpan, content.indexOf("："), content.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
            tv.text = ssb
        }

        private fun setHighlightColorSpan(content: String, tv: TextView) {
            if (content.indexOf(mHighlightStr) != -1){
                val position = content.indexOf(mHighlightStr)
                ssb = SpannableStringBuilder(content)
                ssb!!.setSpan(mHighlightColorSpan, position, mHighlightStr.length, Spannable.SPAN_EXCLUSIVE_INCLUSIVE)
                tv.text = ssb
            }
        }
    }


    interface ClickCallBack{
        fun clickRelieve(item: SpecialMemberEntity?, position : Int)
    }
}